// src/api.js
import axios from 'axios';
import {getToken} from '@/app/apis/common';
import { toast } from 'react-toastify';
const apiBaseUrl = 'http://127.0.0.1:8000'; // 替换为你的 API 地址

const api = axios.create({
    baseURL: apiBaseUrl,
    headers: {
        'Content-Type': 'application/json',
    },
});

// 添加请求拦截器
api.interceptors.request.use(
    (config) => {
        // 从全局状态中获取 access_token
        const accessToken = getToken();
        if (accessToken) {
            config.headers.Authorization = `Bearer ${accessToken}`;
        }
        return config;
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
api.interceptors.response.use(
    (response) => {
        // 对响应数据做点什么
        if (response.data.status === 'success') {
            return response.data;
        } else if (response.data.status === 'error') {
            throw new Error(response.data.message);
        } else if (response.data.status === 'unauthorized') {
            throw new Error('未授权，请重新登录');
        }
        throw new Error('未知错误');
    },
    (error) => {
        // 对响应错误做点什么
        if (error.response) {
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
            if (error.response.data.status === 'error') {
                toast.error("请求错误" + error.response.data.message);
                throw new Error(error.response.data.message);
            } else if (error.response.data.status === 'unauthorized') {
                toast.error("未授权，请重新登录");
                window.location.href = '/auth/login';
                throw new Error('未授权，请重新登录');
            }
        }
        console.error(error)
        throw new Error('网络请求失败');
    }
);

export default api;